package com.dmall.graph.dfs.app;

import com.dmall.graph.Graph;

import java.util.ArrayList;
import java.util.Collections;

public class SingleSourcePathImprove {
    private Graph G;
    private boolean[] visited;
    private int[] pre;
    private int s;
    private int t;

    public SingleSourcePathImprove(Graph G, int s, int t) {
        this.G = G;
        this.s = s;
        this.t = t;
        this.visited = new boolean[G.V()];
        this.pre = new int[G.V()];
        for (int i = 0; i < this.pre.length; i++) {
            this.pre[i] = -1;
        }

        dfs(s, s);

        for (int i = 0; i < visited.length; i++) {
            System.out.print(visited[i] + " ");
        }
        System.out.println();
    }

    private boolean dfs(int v, int p) {
        visited[v] = true;
        pre[v] = p;
        if (v == t) {
            return true;
        }
        for (Integer w : G.adj(v)) {
            if (!visited[w]) {
                if (dfs(w, v)) {
                    return true;
                }
            }
        }
        return false;
    }

    public boolean isCollected() {
        return visited[t];
    }

    public Iterable<Integer> path() {
        ArrayList<Integer> res = new ArrayList<>();
        if (!isCollected()) {
            return res;
        }

        int cur = t;
        while (cur != s) {
            res.add(cur);
            cur = pre[cur];
        }
        res.add(s);
        Collections.reverse(res);
        return res;
    }

    public static void main(String[] args) {
        String filePath = SingleSourcePathImprove.class.getClassLoader().getResource("g.txt").getPath();
        Graph graph = new Graph(filePath);
        SingleSourcePathImprove singleSourcePath = new SingleSourcePathImprove(graph, 0, 6);
        System.out.println(singleSourcePath.path());
    }
}
